package com.gzhryc.html.models;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.apache.commons.lang3.StringUtils;

/**
 * 页面模板
 * @author 张浩
 * @version 2016-10-30
 */
public class HtmlTemplate {
 
	protected String htmlPath;			//页面路径
	protected String realFilePath;		//绝对路径
	
	protected String htmlContent;
	
	public String getHtmlPath() {
		return htmlPath;
	}
	public void setHtmlPath(String htmlPath) {
		this.htmlPath = htmlPath;
	}
	public String getRealFilePath() {
		return realFilePath;
	}
	public void setRealFilePath(String realFilePath) {
		this.realFilePath = realFilePath;
	}
	public synchronized String getHtmlContent() {
		this.htmlContent = readContent();
		return htmlContent;
	}
	public void setHtmlContent(String htmlContent) {
		this.htmlContent = htmlContent;
	}
	
	public String readContent() {
		if(StringUtils.isNotBlank(this.realFilePath)){
			File file = new File(this.getRealFilePath());
			if(file.exists()){
				BufferedReader reader = null;
				try {
					StringBuffer result = new StringBuffer();
					reader = new BufferedReader(new FileReader(file));
					String str = null;
		            while((str = reader.readLine())!=null){
		                result.append(str);
		            }
		            return result.toString();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally{
					try {
						if(reader != null){
							reader.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}
	
	public boolean writeContent() {
		if(StringUtils.isNotBlank(this.realFilePath)){
			File file = new File(this.getRealFilePath());
			if(file.exists()){
				FileOutputStream fileWriter = null;
				OutputStreamWriter writer = null;
				try {
					fileWriter = new FileOutputStream(file);
					writer = new OutputStreamWriter(fileWriter,"UTF-8");
					writer.write(this.htmlContent);
					return true;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally{
					if(writer != null) {
						try {
							writer.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if(fileWriter != null) {
						try {
							fileWriter.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return false;
	}
}
